import { ref, unref, computed } from 'vue';
import { t } from '@src/locales';
import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage';
import { useTimezone, useTimezoneList } from 'pub-bbx-utils';

export const useProps = {
  // 是否使用时区选择器
  useTimezonePicker: {
    type: Boolean,
    default: () => useFormMultiLanguage().internationalGray,
  },
  // 是否编辑模式
  isEdit: {
    type: Boolean,
    default: false,
  },
  // 时间
  value: {
    type: [Array, Number, String, null, undefined],
    default: '',
  },
  // 默认时间点
  defaultTime: {
    type: [Array, String],
    default: null,
  },
  // 时间类型
  type: {
    type: String,
    default: 'date',
  },
  // 时间格式化模板
  valueFormat: {
    type: [String, undefined],
  },
  format: {
    type: [String, undefined],
  },
  placeholder: {
    type: String,
    default: () => t('common.placeholder.select'),
  },
  // 时区
  timezone: {
    type: String,
    default: useTimezone().timezone,
  },
  // elPopper的属性透传
  popoverProps: {
    type: Object,
    default: () => ({}),
  },
  pickerOptions: {
    type: Object,
    default: () => ({}),
  },
  pickerPopperClass: {
    type: String,
    default: '',
  },
  prefixIcon: {
    type: String,
    default: () => 'iconfont icon-fdn-datetime',
  },
  field: {
    type: Object,
    default: () => ({})
  }
};

/**
 * 时区选择器
 * @returns
 */
export function useTimezonePicker(timezone: string) {
  const cacheKey = 'BBX_TIMEZONE_PICKER_TIMEZONE';
  const { zoneIdMap, getTimezoneList } = useTimezoneList();
  // 时区
  const pickerTimezone = ref(timezone || useTimezone().timezone);
  const backTimezone = ref('');
  getTimezoneList().then(() => {
    backTimezone.value = zoneIdMap.get(unref(pickerTimezone))?.zoneId || '';
  });
  const isShowTimezone = computed(() => unref(backTimezone) !== unref(pickerTimezone));

  // 切换时区
  function changeTimezone(timezone: string = useTimezone().timezone) {
    pickerTimezone.value = zoneIdMap.get(timezone)?.zoneId ?? timezone;
    setTimezoneCache();
  }

  // 设置时区缓存
  function setTimezoneCache() {
    sessionStorage.setItem(cacheKey, pickerTimezone.value);
  }

  // 使用缓存的时区
  function useTimezoneCache() {
    return (pickerTimezone.value = sessionStorage.getItem(cacheKey) ?? unref(pickerTimezone));
  }

  return {
    pickerTimezone,
    isShowTimezone,
    changeTimezone,
    setTimezoneCache,
    useTimezoneCache,
  };
}
